<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.sessionID"
        placeholder="会话ID"
        style="width: 200px"
        class="filter-item"
      />
      <el-input
        v-model="listQuery.sessionName"
        placeholder="会话名称"
        style="width: 200px"
        class="filter-item"
      />
      <el-input
        v-model="listQuery.roomName"
        placeholder="房间名称"
        style="width: 200px"
        class="filter-item"
      />
      <el-select
        v-model="listQuery.importance"
        placeholder="重要度"
        clearable
        style="width: 120px"
        class="filter-item"
      >
        <el-option
          v-for="item in importanceOptions"
          :key="item.key"
          :label="item.display_name"
          :value="item.key"
        />
      </el-select>
      <el-select
        v-model="listQuery.type"
        placeholder="查询类型"
        clearable
        class="filter-item"
        style="width: 130px"
      >
        <el-option
          v-for="item in itemTypeOptions"
          :key="item.key"
          :label="item.display_name"
          :value="item.key"
        />
      </el-select>
      <!-- <el-select
        v-model="listQuery.sort"
        style="width: 140px"
        class="filter-item"
        @change="handleFilter"
      >
        <el-option
          v-for="item in sortOptions"
          :key="item.key"
          :label="item.label"
          :value="item.key"
        />
      </el-select> -->
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleQuery"
      >
        查询
      </el-button>
      <el-button
        v-waves
        :loading="downloadLoading"
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        @click="handleDownload"
      >
        导出
      </el-button>
      <el-button
        v-waves
        class="filter-item"
        type="warning"
        icon="el-icon-delete"
        @click="handleTruncate"
      >
        清空
      </el-button>
      <!-- <el-checkbox
        v-model="showReviewer"
        class="filter-item"
        style="margin-left: 15px"
        @change="tableKey = tableKey + 1"
      >
        reviewer
      </el-checkbox> -->
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
      :default-sort="{prop: 'id'}"
      @row-dblclick="handleClickRow"
    >
      <el-table-column
        label="序号"
        prop="id"
        sortable
        align="center"
        min-width="20"
        :class-name="getSortClass('id')"
      >
        <template slot-scope="{ row }">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="时间" min-width="50" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.time }}</span>
        </template>
      </el-table-column>
      <el-table-column label="模块" width="130px" align="center">
        <template slot-scope="{ row }">
          <div v-if="row.tomodule===-1">
            <el-tag :type="row.frommodule | moduleTypeFilter">{{ row.frommoduleno | moduleFilter }}</el-tag>
          </div>
          <div v-else>
            <el-tag :type="row.frommodule | moduleTypeFilter">{{ row.frommoduleno | moduleFilter }}</el-tag> -> <el-tag :type="row.tomodule | moduleTypeFilter">{{ row.tomoduleno | moduleFilter }}</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="标题" min-width="80px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.subject }}</span>
        </template>
      </el-table-column>
      <el-table-column label="重要性" min-width="30px">
        <template slot-scope="{row}">
          <svg-icon v-for="n in + row.prority" :key="n" icon-class="star" class="meta-item__icon" />
        </template>
      </el-table-column>
      <el-table-column label="sessionid" min-width="40px">
        <template slot-scope="{ row }">
          <span>{{ row.sessionid }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户名" min-width="40px">
        <template slot-scope="{ row }">
          <span>{{ row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column label="房间名" min-width="40px">
        <template slot-scope="{ row }">
          <span>{{ row.roomname }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        min-width="30"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row, $index }">
          <el-button type="primary" size="mini" @click="handleDetail(row, $index)">
            详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" class="box-card-component">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="detail"
        label-position="left"
        label-width="70px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item label="重要程度">
          <svg-icon v-for="n in + detail.prority" :key="n" icon-class="star" class="meta-item__icon" />
        </el-form-item>
        <el-form-item label="方向">
          <el-tag :type="detail.frommodule | moduleTypeFilter">{{ detail.frommoduleno | moduleFilter }}</el-tag> -> <el-tag :type="detail.tomodule | moduleTypeFilter">{{ detail.tomoduleno | moduleFilter }}</el-tag>
        </el-form-item>
        <el-form-item label="时间">
          <div><i class="el-icon-time" /> {{ detail.time }}</div>
        </el-form-item>
        <el-form-item label="标题">
          <!-- <el-input v-model="detail.subject" :disabled="true" /> -->
          <div class="grid-content bg-purple-light">{{ detail.subject }}</div>
        </el-form-item>
        <el-form-item label="内容">
          <div style="white-space: pre-line" v-html="detail.detail" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <!-- <el-button @click="dialogFormVisible = false"> Cancel </el-button> -->
        <el-button type="primary" @click="closeDetail()"> 关闭 </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

// const sdkOptions = {
//   websocketurl: 'wss://meeting.zwan.com.cn:2237/log', // websocket信令服务URL
//   oamurl: 'https://meeting.zwan.com.cn:2237', // 管理服务URL
//   stunurl: 'stun:stun.zwan.com.cn:2231' // stun服务器地址
//   // websocketurl: 'wss://113.207.109.120:40004/log', // websocket信令服务URL
//   // oamurl: 'https://113.207.109.120:40004', // 管理服务URL
//   // stunurl: 'stun:113.207.109.120:40000' // stun服务器地址
//   // websocketurl: 'wss://172.20.215.193:2337/log', // websocket信令服务URL
//   // oamurl: 'https://172.20.215.193:2337', // 管理服务URL
//   // stunurl: 'stun:172.20.215.193:2331' // stun服务器地址

// }

const itemTypeOptions = [
  { key: 'message', display_name: '消息' },
  { key: 'event', display_name: '事件' },
  { key: 'all', display_name: '全部' }
]

const itemProrityOptions = [
  { key: 1, display_name: '所有日志' },
  { key: 2, display_name: '普通事件' },
  { key: 3, display_name: '关键事件' },
  { key: 4, display_name: '严重错误' }
]

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      sessionid: 0,
      tableKey: 0,
      allList: [],
      list: [],
      total: 0,
      listLoading: false,
      startQuery: false,
      listQuery: {
        page: 1,
        limit: 10,
        importance: 2,
        sessionID: undefined,
        sessionName: undefined,
        roomName: undefined,
        type: 'all',
        sort: '+id'
      },
      importanceOptions: itemProrityOptions,
      itemTypeOptions,
      sortOptions: [
        { label: 'ID Ascending', key: '+id' },
        { label: 'ID Descending', key: '-id' }
      ],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      detail: { prority: 0 },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        detail: '详情'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [
          { required: true, message: 'type is required', trigger: 'change' }
        ],
        timestamp: [
          {
            type: 'date',
            required: true,
            message: 'timestamp is required',
            trigger: 'change'
          }
        ],
        title: [
          { required: true, message: 'title is required', trigger: 'blur' }
        ]
      },
      downloadLoading: false
    }
  },
  created() {
    this.$tvvssdk.init(this.$sdkOptions, function(res) {
      if (res.success) {
        console.log('sdk初始化成功')
      } else {
        alert(res.msg)
      }
    })
    this.getList()
  },
  mounted() {
    const _this = this
    this.$tvvssdk.createConnection(function(res) {
      if (res.success) {
        _this.sessionid = res.sessionid
        console.log('服务器连接成功 sessionid:' + _this.sessionid)
        if (_this.startQuery) {
          _this.handleQuery()
        }
      } else {
        console.log(res.msg)
      }
    })

    this.startQuery = false

    if (this.$route.params.sessionid) {
      this.listQuery.sessionID = this.$route.params.sessionid.toString()
      this.startQuery = true
    }

    if (this.$route.params.roomname) {
      this.listQuery.roomName = this.$route.params.roomname
      this.startQuery = true
    }
  },
  methods: {
    moduleTypeText(type) {
      const statusMap = {
        0: 'rtcgw', // rtcgw
        1: 'zwmp', // zwmp
        2: 'sip', // sip
        3: 'web', // web
        4: 'oam' // oam
      }
      return statusMap[type]
    },
    getList() {
      this.list = this.allList.slice((this.listQuery.page - 1) * this.listQuery.limit, this.listQuery.page * this.listQuery.limit)
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleQuery() {
      this.listQuery.page = 1
      const _this = this
      this.$tvvssdk.queryLog(this.sessionid,
        this.listQuery.sessionID,
        this.listQuery.sessionName,
        this.listQuery.roomName,
        this.listQuery.importance,
        this.listQuery.type,
        function(res) {
          if (res.success) {
            _this.allList = res.logs
            _this.list = _this.allList.slice((_this.listQuery.page - 1) * _this.listQuery.limit, _this.listQuery.page * _this.listQuery.limit)
            _this.total = res.logs.length
          }
        })
    },
    handleTruncate() {
      this.listQuery.page = 1
      const _this = this
      this.$tvvssdk.truncateLog(this.sessionid,
        function(res) {
          if (res.success) {
            _this.allList = []
            _this.list = []
            _this.total = 0
          }
        })
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    handleClickRow(row, column, event) {
      console.log(row)
      this.handleDetail(row, row.id)
    },
    handleDetail(row, index) {
      this.detail = row
      this.dialogStatus = 'detail'
      this.dialogFormVisible = true
    },
    closeDetail() {
      this.dialogFormVisible = false
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then((excel) => {
        const tHeader = ['时间', '方向', '标题', '重要性', 'sessionid', '用户名', '房间名']
        const filterVal = [
          'time',
          'frommoduleno',
          'subject',
          'prority',
          'sessionid',
          'username',
          'roomname'
        ]
        const data = this.formatJson(filterVal)
        debugger
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map((v) =>
        filterVal.map((j) => {
          if (j === 'sessionid') {
            return v[j].toString()
          } else if (j === 'frommoduleno') {
            return this.moduleTypeText(v['frommodule']) + ' ' + v['frommoduleno'] + '->' +
              this.moduleTypeText(v['tomodule']) + ' ' + v['tomoduleno']
          } else {
            return v[j]
          }
        })
      )
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>

<style lang="scss" >
.box-card-component {
  .el-card__header {
    padding: 0px !important;
  }
  .el-card__body {
    padding: 0px !important;
  }
}
</style>
<style lang="scss" scoped>
.box-card-component {
  .box-card-header {
    position: relative;
    height: 220px;
    img {
      width: 100%;
      height: 100%;
      transition: all 0.2s linear;
      &:hover {
        transform: scale(1.1, 1.1);
        filter: contrast(130%);
      }
    }
  }
  .card-panel-text {
    line-height: 18px;
    color: rgba(0, 0, 0, 0.55);
    font-size: medium;
    font-weight: bold;
    margin-top: 14px;
    margin-left: 14px;
  }
  .progress-item {
    margin-bottom: 10px;
    font-size: 14px;
  }
  .el-header,
  .el-footer {
    background-color: #b3c0d1;
    color: #333;
    text-align: center;
    line-height: 60px;
  }

  .el-aside {
    background-color: #d3dce6;
    color: #333;
    div {
      text-align: center;
      vertical-align: middle;
      display: table-cell;
      margin: auto;
    }
  }

  .el-main {
    background-color: #e9eef3;
    color: #333;
    text-align: center;
    vertical-align: middle;
    line-height: 40px;
  }

  body > .el-container {
    margin-bottom: 40px;
  }

  .el-container:nth-child(5) .el-aside,
  .el-container:nth-child(6) .el-aside {
    line-height: 260px;
  }

  .el-container:nth-child(7) .el-aside {
    line-height: 320px;
  }
  .el-row {
    margin-bottom: 20px;
    &:last-child {
      margin-bottom: 0;
    }
  }
  .el-col {
    border-radius: 4px;
  }
  .bg-purple-dark {
    background: #99a9bf;
  }
  .bg-purple {
    background: #d3dce6;
  }
  .bg-purple-light {
    background: #e5e9f2;
  }
  .grid-content {
    border-radius: 4px;
    min-height: 36px;
    text-align: center;
    vertical-align: middle;
  }
  .row-bg {
    padding: 10px 0;
    background-color: #f9fafc;
  }
  @media only screen and (max-width: 1510px) {
    .mallki-text {
      display: none;
    }
  }
}
</style>
